package filelisting

import (
	"net/http"
	"fmt"
	"strings"
	"os"
	"io/ioutil"
)

const prefix = "/list/"

type userError string

func (e userError) Error() string{
	return e.Message()
}
func (e userError) Message() string {
	return string(e)
}

func HandleFileList(writer http.ResponseWriter,
	request *http.Request) error{
		fmt.Println()
	if strings.Index(request.URL.Path, prefix) != 0{
		return userError(
			fmt.Sprintf("path %s must start with %s",
				request.URL.Path, prefix),
		)
	}
	path := request.URL.Path[len(prefix):]
	file, err := os.Open(path)
	defer file.Close()
	if err != nil {
		return err
	}

	if all, err := ioutil.ReadAll(file); err != nil{
		return nil
	} else {
		writer.Write(all)
	}
	return nil
}